(function(window){
	var document = window.document;
	var canjs = function(selector){      
		if ( window == this ) return new canjs(selector);
		var length=0;
		
		if(typeof selector == 'function'){	
			canjs._addEvent(window,'load',selector);
			return this;
			
		}else if(typeof selector=='object'){
			this[0]=selector;
			this.length=1;
			
		}else if(typeof selector == 'string'){
			var rs=[];
			rs=canjs._domQuery(selector);
			for(var i=0; i< rs.length;i++){
				this[i]=rs[i];
			}
			this.length=rs.length;
			rs=null;
			
		}else{
			return this;
		}
			
		canjs._event();
		return this;
	}
	
	canjs.trim = function(value){
		return value.replace(/^\s+|\s+/g,'');	
	}
	
	canjs.param= function(object){
		if(typeof object== 'object'){
			var s = [];
			for(var i in object){
				s[ s.length ] = encodeURIComponent( i ) + "=" + encodeURIComponent( object[i] );
			}
			return s.join( "&" ).replace( /%20/g, "+" );	
		}	
	}
	
	//dom
	canjs._domQuery = function(selector){
		var rs=[];
		selector=canjs.trim(selector);
		
		if(selector.charAt(0)=='#'){
			selector=selector.replace(/^(#)/,'')
			rs[0]=document.getElementById(selector);
			
		}else if(selector.charAt(0)=='.'){
			selector=selector.replace(/^(\.)/,'');
			var ele=document.getElementsByTagName('*');
			for(var i=0,j = 0; j < ele.length; j++){
				if(ele[j].className==selector){
					rs[i++]=ele[j];
				}
			}
			ele=null;
		}else{
			rs=document.getElementsByTagName(selector);
		}	    
		return rs;
	}
	
	//event
	canjs._addEvent = function( obj, type, fn ) {
		if( obj.attachEvent ) {
			obj[ 'e' + type + fn ] = fn;
			obj[ type + fn ] = function() {
				obj[ 'e' + type + fn ]( window.event );
			}
			obj.attachEvent( 'on' + type, obj[ type + fn ]);
		}else {	
			obj.addEventListener( type, fn, false );
		}
	}
	
	canjs._event = function(){
		var eventArr=("blur,focus,load,resize,scroll,unload,click,dblclick," +
		"mousedown,mouseup,mousemove,mouseover,mouseout,change,select," + 
		"submit,keydown,keypress,keyup").split(",");
		
		for(var i in eventArr){
			(function(type){
				canjs.prototype[type] = function(fn){				
					this.each(function(el){
						if(typeof fn == 'function'){
							canjs._addEvent(el, type, fn);
						}else{
							el[type]();	
						}
						
					});	
				}
			})(eventArr[i]);
		}
		
		eventArr=null;
		return this;
	}
	
	//method		
	canjs.prototype = canjs.fn = {
		
		each : function(fn){
			for (var i = 0; i < this.length; i++) {
				fn.call(this, this[i]); 
			}	
		},
		
		html : function(value){
			if(typeof value == 'undefined'){ 	
				var rs=[];					
				this.each(function(el){ 
					rs.push(el.innerHTML) ;
				});
				return rs;
			} else { 		
				this.each(function(el){
					el.innerHTML= value;
				});
				return this;
			}
		},	
		
		val : function(value){
			if(typeof value == 'undefined'){ 	
				var rs=[];					
				this.each(function(el){ 
					rs.push(el.value) ;
				});
				return rs;
			} else { 		
				this.each(function(el){
					el.value = value;
				});
				return this;
			}
		},	
	
		append : function(value){	
			if ( typeof value == "string" ) {
				this.each(function(el){
					el.innerHTML = el.innerHTML + value;
				});
			}
			return this;
		},
				
		show : function(){
			this.each(function(el){
				el.style.display="";
			});
			return this;
		},
		
		hide : function(){
			this.each(function(el){
				el.style.display="none";
			});
			return this;
		},
			
		attr : function(name,value){
			if(typeof value == 'undefined'){ 	
				var rs=[];
				this.each(function(el){ 
					rs.push(el.getAttribute(name)) ;
				});
				return rs;
			}else{ 		
				this.each(function(el){
					el.setAttribute(name,value);
				});
				return this;
			}
		},
		
		css : function(name,value){
			if(typeof value == 'undefined'){ 	
				var rs=[];
				this.each(function(el){ 
					rs.push( el.currentStyle?el.currentStyle[name]:document.defaultView.getComputedStyle(el,false)[name]);
				});
				return rs;
			}else{ 		
				this.each(function(el){
					 el.style[name]	= value;		  
				});
				return this;
			}
		},
		
		extend : function(object){
			for(var i in object){
				if(typeof object[i] == 'function'){
					 canjs.fn[i]=object[i];
					 if(typeof jQuery != 'undefined'){
						 jQuery.fn[i]=object[i];
					 }
				}			
			}
			return this;
		}
		
	};
		
	//ajax
	canjs.ajax = function(opt){
		var xmlHttp = null;
		var aborted=false;
		var timeoutHandle; 
		var options={
						 type:'GET', 
						 url:'test.php',
						 data:'', 
						 async:true,
						 cache:false,
						 timeout:30000,
						 dataType:'text',
						 success:function(msg){}, 
						 error:function(msg){alert(msg);}
					}
	
		if(typeof opt== 'object'){	
			for(var pro in opt){  
				options[pro] = opt[pro];
			 }
		} 
		
		this.createXMLHttpRequest=function (){
			if(xmlHttp != null) return;
			if (window.ActiveXObject) {
				try {
					xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
			}else if (window.XMLHttpRequest) {
				xmlHttp = new XMLHttpRequest();
			}
		}
	
		this.sendData = function(){			   
			xmlHttp.onreadystatechange = function() {
				if (!aborted&&xmlHttp.readyState == 4) {
					if (!aborted&&xmlHttp.status == 200) {
						clearTimeout(timeoutHandle);
						switch(options.dataType.toLowerCase()){
							case 'xml':data= xmlHttp.responseXML; break;
							case 'json':data=eval('(' + xmlHttp.responseText + ')'); break;
							default:data= xmlHttp.responseText; 						
						}
						options.success(data);
					}else {
						options.error(xmlHttp.status.toString());
					}
				}
			}
			if (typeof options.data =='object') {
				options.data=canjs.param(options.data);
			}		
			if (options.type.toLowerCase() == "get"){
				if (options.data != "") {		
					if(options.url.indexOf("?")>=0){    
							 options.url =options.url+ "&" + options.data; 
					 }else{    
						 options.url =options.url+ "?" + options.data; 
					 }  
				}
				options.url=encodeURI(options.url);
				xmlHttp.open("GET", options.url, options.async);
				if (!options.cache) {xmlHttp.setRequestHeader("Cache-Control","no-cache");}
				xmlHttp.send(null);
			} else {
				xmlHttp.open("POST", options.url, options.async);
				if (!options.cache) {xmlHttp.setRequestHeader("Cache-Control","no-cache");}   
				xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				xmlHttp.send(options.data);
			}
		}
		
		this.checkTimeout = function(){
			if(xmlHttp.readyState!=null&&xmlHttp.readyState!=4){ 
				aborted=true; 
				xmlHttp.abort();
				options.error('timeout');
			}
		}
		
		try {
			this.createXMLHttpRequest();
			timeoutHandle=setTimeout("this.checkTimeout",options.timeout); 
			this.sendData();
		}catch (e) {options.error(e.toString());}
	}
	
	canjs._ajax = function(method,url,data,callback,type)
	{
		data=(typeof data == 'undefined')?'':data;
		callback=(typeof callback == 'undefined')?function(msg){}:callback;
		type=(typeof type == 'undefined')?'text':type;
		
		if(typeof data == 'function'){
			type=(typeof callback == 'string')?callback:type;
			callback=data;	
			data='';
		}		
		return canjs.ajax({
				 type:method, 
				 url:url,
				 data:data, 
				 dataType:type,
				 success:callback
			 });
	}
	
	canjs.get = function(url,data,callback,type){
		return canjs._ajax('GET',url,data,callback,type);
	}
	
	canjs.post = function(url,data,callback,type){
		return canjs._ajax('POST',url,data,callback,type);
	}

	canjs.getJSON = function(url,data,fn){
		var param="";
		switch(typeof data ){
			case 'string': param=data; break;
			case 'object': param='&'+canjs.param(data); break;
			case 'function': fn=data; break;
			default:break;
		}
		
		var callback_fn='';
		for(var i=0; i<100;i++){
			callback_fn='jsonp'+new Date().getTime()+parseInt(100*Math.random());
			if(typeof window[callback_fn]=='undefined'){
				window[callback_fn] = function(data){
					if(typeof fn=='function'){
						fn(data);
					}
					window[callback_fn]=null;
				}
				break;
			}
		}

		url=url.replace(/(\?)$/,callback_fn)+param;
		var head = document.getElementsByTagName("head")[0] || document.documentElement;  
		var script = document.createElement("script");   
		head.insertBefore( script, head.firstChild );   
		script.setAttribute("type", "text/javascript");  
		script.setAttribute("src", url); 		
	}
	
	//extend	
	canjs.extend = function(object){
		for(var i in object){
			if(typeof object[i]== 'function'){
				 canjs[i]=object[i];
				 if(typeof jQuery != 'undefined'){
					jQuery[i]=object[i];
				 }
			}			
		}
		return this;
	}
	
	canjs.fn.extend({
		'enter':function(fn){ 
			this.keydown(function(e){ 
				if(e.keyCode==13){
						fn();
				}							
			});
		}	
	});
				
	canjs.extend({
		cookie: function(name, value, options){
				if (typeof value != 'undefined') { 
					options = options || {};
					if (value === null) {
						value = '';
						options.expires = -1;
					}
					var expires = '';
					if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
						var date;
						if (typeof options.expires == 'number') {
							date = new Date();
							date.setTime(date.getTime() + (options.expires * 1000));
						} else {
							date = options.expires;
						}
						expires = '; expires=' + date.toUTCString(); 
					}
					
					var path = options.path ? '; path=' + options.path : '';
					var domain = options.domain ? '; domain=' + options.domain : '';
					var secure = options.secure ? '; secure' : '';
					document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
				} else {
					var cookieValue = null;
					if (document.cookie && document.cookie != '') {
						var cookies = document.cookie.split(';');
						for (var i = 0; i < cookies.length; i++) {
							var cookie = cookies[i].toString().replace( /^\s+/, "" ).replace(/\s+$/, "" );

							if (cookie.substring(0, name.length + 1) == (name + '=')) {				
								cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
								break;
							}
						}
					}
					return cookieValue;
				}
			},
			
		dump: function(data,isReturn){			
		      var _print = function(o, depth,n) {
			          var result = '';
			          depth || (depth=1);
			          n || (n=1);		
			          var indent = new Array(4*depth+1).join(' ');
			          var indentNext = new Array(4*(depth+1)+1).join(' ');
			          var indentNextTwo = new Array(4*(depth+2)+1).join(' ');
			          var tmp = '';
			          var type = typeof o;
			          if(depth==1) {
							if(type=='string'||type=='number'||type=='boolean'){
								return o;
							}
							if(type=='undefined'){
								return 'undefined';
							}
			          }
			          
			          switch(type) {
			            case 'string':
			            case 'number':
			            case 'boolean':
			            case 'undefined':
			            case 'function':
			              tmp += indent + indentNext + o + "\n";
			              break;
			            case 'object':
			            default:
			              for(var key in o) {
			                tmp += indentNextTwo + '[' + key + '] = ';
			                try{
			               		 n<=20?(tmp += _print(o[key], (depth+1),n++)) : '';
			                }catch(e){}
			              }
			          }
			          result += type + "\n";
			          result += indentNext + '(' + "\n";
			          result += tmp;
			          result += indentNext + ')' + "\n";
			          return result;
	     		 };
	     	 
				if(isReturn){ 
					return _print(data); 
				}else{
					 alert(_print(data));
				};
			},
			
		checkbox : function(name,action){
				var el=document.getElementsByName(name); 
				for (var i=0;i<el.length;i++){ 
					if(el[i].type=="checkbox"&&el[i].name==name){ 
						switch(action){
							case 1:el[i].checked=true; break;
							case -1:
									if(el[i].checked==true){ 
										el[i].checked=false;
									}else{ 
										el[i].checked=true;
									}
								    break;
							default:el[i].checked=false; 
						}			
					} 
				} 
			}
			
	});
	
	window.canjs=canjs;
		
	if(typeof window.$ =="undefined"){
		window.$=window.canjs;
	}
})(window);
